import axios from "axios";
import config from "../config.js";
import router from "../router";
import { Loading, Message } from "element-ui";

axios.defaults.baseURL = config.baseURL;
// 请求拦截
axios.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem("Authorization");
    config.headers.Authorization = token;
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);
// 响应拦截
axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response.data;
  },
  function (error) {
    // 对响应错误做点什么
    if (error.response.status === 401) {
      Message({
        message: error.response.data.msg || error.response.data.error,
        type: "error",
        onClose: () => {
          router.replace({
            path: "/login",
          });
        },
      });
    } else {
      Message({
        message: error.response.data.msg||error.response.data.message,
        type: "error",
      });
    }
    return Promise.reject(error);
  }
);

export default axios;
